﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Text;
using System.Threading.Tasks;
using DotNetMVC.DTO;
using DotNetMVC.IService;
using DotNetMVC.Model;

namespace DotNetMVC.Service
{
    public partial class PermissionService : BaseService<Permission>, IPermissionService
    {
        /// <summary>
        /// 权限名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Exist(string name)
        {
            return GetAll().Any(p => p.Name == name); ;
        }

        public PermissionDTO[] GetPermissions()
        {
            return GetAll().ToList().Select(p => ToDTO(p)).ToArray();
        }

        /// <summary>
        /// 获取管理员权限菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public PermissionDTO[] GetPermMenusByUserId(long userId)
        {
            return DbSession.PermissionDal.GetPermMenusByUserId(userId).ToList().Select(p => ToDTO(p)).ToArray();
        }

        #region 递归获取权限
        /// <summary>
        /// 递归获取权限
        /// </summary>
        /// <param name="permissionLevel">权限级数， 不指定，默认返回全部</param>
        /// <returns></returns>
        public List<PermissionDTO> GetPermissionsByLevel(int permissionLevel = 0)
        {
            PermissionDTO[] allPermission = GetPermissions();
            return GetGetPermissions(allPermission, 0, permissionLevel);
        }

        /// <summary>
        /// 递归获取权限
        /// </summary>
        /// <param name="allPermission"></param>
        /// <param name="parentId"></param>
        /// <param name="permissionLevel"></param>
        /// <returns></returns>
        private List<PermissionDTO> GetGetPermissions(PermissionDTO[] allPermission, long parentId, int permissionLevel)
        {
            List<PermissionDTO> list = new List<PermissionDTO>();
            //默认获取全部权限
            IEnumerable<PermissionDTO> childPermissions = allPermission.Where(e => e.ParentId == parentId);
            if (permissionLevel != 0)
            {
                //获取指定级数权限
                childPermissions = childPermissions.Where(e => e.PermissionLevel <= permissionLevel);
            }

            //没有子权限
            if (childPermissions.Count() <= 0)
            {
                return list;
            }

            foreach (PermissionDTO dto in childPermissions)
            {
                list.Add(dto);
                //递归获取子权限
                list.AddRange(GetGetPermissions(allPermission, dto.Id, permissionLevel));
            }

            return list;
        }
        #endregion

        public PermissionDTO GetDTOById(long id)
        {
            Permission entity = GetById(id);
            if (entity==null)
            {
                //throw new Exception("获取不到权限(Id:" + id + ")信息");
                return null;
            }
            return ToDTO(entity);
        }

        /// <summary>
        /// 角色拥有权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public PermissionDTO[] GetPermissionByRoleId(long roleId)
        {
            //角色是否存在
            Role role = DbSession.RoleDal.GetById(roleId);
            if (role == null)
            {
                throw new ArgumentException("roleId 不存在" + roleId);
            }
            return role.RolePermissions.Select(rp => ToDTO(rp.Permission)).ToArray();
        }

        private PermissionDTO ToDTO(Permission entity)
        {
            PermissionDTO dto = new PermissionDTO();
            dto.CreateDateTime = entity.CreateDateTime;
            dto.Id = entity.Id;
            dto.Name=entity.Name;
            dto.Description=entity.Description;
            dto.ControllerName=entity.ControllerName;
            dto.ActionName=entity.ActionName;
            dto.HttpMethod=entity.HttpMethod;
            dto.IsMenu = entity.IsMenu;
            dto.MenuIcon = entity.MenuIcon;
            dto.ParentId = entity.ParentId;
            dto.PermissionLevel = entity.PermissionLevel;
            return dto;
        }

        public void Add(PermissionDTO modelParentPermission, string name, bool isMenu, string menuIcon, string description, string controllerName, string actionName, string httpMethod)
        {
            Permission entity = new Permission();
            entity.Name = name;
            entity.Description = description;
            entity.ControllerName = controllerName;
            entity.ActionName = actionName;
            entity.HttpMethod = httpMethod;
            entity.IsMenu = isMenu;
            entity.MenuIcon = menuIcon;
            if (modelParentPermission==null)
            {
                entity.ParentId = 0;
                entity.PermissionLevel = 1;
            }
            else
            {
                entity.ParentId = modelParentPermission.Id;
                entity.PermissionLevel = modelParentPermission.PermissionLevel+1;
            }
            Add(entity);
        }
        public void Update(long id, PermissionDTO modelParentPermission, string name, bool isMenu, string menuIcon, string description, string controllerName, string actionName, string httpMethod)
        {
            Permission entity = GetById(id);
            if (entity==null)
            {
                throw new Exception("获取不到权限(id:"+id+")信息");
            }
            entity.Name = name;
            entity.Description = description;
            entity.ControllerName = controllerName;
            entity.ActionName = actionName;
            entity.HttpMethod = httpMethod;
            entity.IsMenu = isMenu;
            entity.MenuIcon = menuIcon;
            if (modelParentPermission == null)
            {
                entity.ParentId = 0;
                entity.PermissionLevel = 1;
            }
            else
            {
                entity.ParentId = modelParentPermission.Id;
                entity.PermissionLevel = modelParentPermission.PermissionLevel + 1;
            }
            Update(entity);
        }
    }
}
